<?php

/**
 *   OPENSHOP 商品批量上传、修改
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: goods_batch.php,v 1.0 2009/06/17 08:56:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');
require('includes/lib_goods.php');

/*------------------------------------------------------ */
//-- 批量上传
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'add')
{
    /* 检查权限 */
    admin_priv();

    /* 取得分类列表 */
    $smarty->assign('cat_list', cat_list());

    /* 取得可选语言 */
    $dir = opendir(SOURCE_PATH . 'languages');
    $lang_list = array(
        'UTF8'   => '国际化编码（utf8）',
        'GB2312' => '简体中文',
        'BIG5'   => '繁体中文',
    );
    $download_list = array();
    while (@$file = readdir($dir))
    {
        if ($file != '.' && $file != '..' && $file != ".svn" && $file != "_svn" && is_dir(SOURCE_PATH . 'languages/' .$file) == true)
        {
            $download_list[$file] = sprintf('下载批量xls文件（%s）', isset($_LANG['charset'][$file]) ? $_LANG['charset'][$file] : $file);
        }
    }
    @closedir($dir);
    
    $smarty->assign('lang_list',     $lang_list);
    $smarty->assign('download_list', $download_list);

    /* 参数赋值 */
    $ur_here = '批量初始化数据上传';
    $smarty->assign('ur_here', $ur_here);

    drop_tmp_batch_goods_csv();
    /* 显示模板 */
    assign_query_info();
	
	$smarty->display('goods_batch_add.tpl');
}

/*------------------------------------------------------ */
//-- 批量处理：选择压缩包
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'file_select')
{
	require_once('./includes/filetype.php');
	$rootdir = SOURCE_PATH.'temp/goods_package/';	
	$type = isset($type) ? $type : 'thumb';
	$currentdir = isset($_GET['currentdir']) ? $_GET['currentdir'] : '';
	drop_tmp_batch_goods_csv();
	$parentdir = isset($_GET['parentdir']) ? $_GET['parentdir'] : '';
	$thisdir = dir_path($rootdir.$currentdir);
	if($currentdir && !preg_match("/^[0-9a-z_\/]+$/i",$currentdir)) die("参数错误！");
	if($parentdir && !preg_match("/^[0-9a-z_\/]+$/i",$parentdir)) die("参数错误！");
	if(!is_dir($thisdir)) die("当前目录".$thisdir."不存在！");
	$listdirs = array();
	$listfiles = array();
	$list = glob($thisdir."*");
	$files = glob($thisdir."*.*");
	if(!$list) $list = array();
	if(!$files) $files = array();
	$dirs = array_diff($list, $files);
	
	if(is_array($dirs))
	{
		foreach($dirs as $k=>$v)
		{
			$ldir['name'] = basename($v);
			$ldir['path'] = ($currentdir ? dir_path($currentdir) : '').$ldir['name'];
			$ldir['type'] = "文件夹";
			$ldir['size'] = "<目录>";
			$ldir['mtime'] = date("Y-m-d H:i:s",filemtime($v));
			$listdirs[] = $ldir;
		}
	}
	
	if(is_array($files))
	{
		foreach($files as $k=>$v)
		{
			$ext = fileext($v);
			$lfile['ext']  =  array_key_exists($ext,$filetype) ? $ext : "other";
			$lfile['type'] = $filetype[$lfile['ext']];
			$lfile['path'] = str_replace(SOURCE_PATH.'temp', 'temp', $v);
		    $lfile['name'] = basename($v);
			$lfile['size'] = round(filesize($v)/1000);
			$lfile['mtime'] = date("Y-m-d H:i:s",filemtime($v));
			$listfiles[] = $lfile;
		}
	}
	$backparentdir = dirname($parentdir) == '.' ? '' : dirname($parentdir);	
	$smarty->assign('file_sel_guide',array('currentdir'=>$currentdir,
	                                       'backparentdir'=>$backparentdir,
	                                       'parentdir'=>$parentdir,
	                                       
	                                       'listdirs'=>$listdirs,
	                                       'listfiles'=>$listfiles));
	drop_tmp_batch_goods_csv();
	
	$smarty->display('file_select.tpl');	
}
/*------------------------------------------------------ */
//-- 批量上传：处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'upload')
{
    /* 检查权限 */
    //admin_priv('goods_batch');
    ini_set('max_execution_time',0);
    
    if(file_exists($_FILES['file']['tmp_name']))
	{
	    require_once('./includes/xls_reader.php');
	    
	    $data = new Spreadsheet_Excel_Reader();
	    //$data->setOutputEncoding('CP936');
	    $data->setOutputEncoding('UTF-8');
	    $data->read($_FILES['file']['tmp_name']);
	    
	    error_reporting(E_ALL ^ E_NOTICE);
	    
	    $goods_arr = array();
		//××××××××××××××××处理第一张表【商品信息】，从第2行开始取数据×××××××××××××××××××××
		
		$sheetNo = 0; 
		
		for ($i = 2; $i <= $data->sheets[$sheetNo]['numRows']; $i++) {
			//商品编码
			$code = $data->sheets[$sheetNo]['cells'][$i][1];
			//商品名称
			$g_name = $data->sheets[$sheetNo]['cells'][$i][2];
			//分类ID
			$cf_id = $data->sheets[$sheetNo]['cells'][$i][3];
			//商品描述
			$desc = $data->sheets[$sheetNo]['cells'][$i][4];
			//商品关键字
			$keywords = $data->sheets[$sheetNo]['cells'][$i][5];
			//买家备注
			$mark = $data->sheets[$sheetNo]['cells'][$i][6];
			//尺码对照表ID
			$size_compare = $data->sheets[$sheetNo]['cells'][$i][7];

			//********更新商品表基础信息**************
			if(!empty($code)){
				$sql = "UPDATE " . $os->table('goods') . " SET ";
				if(!empty($g_name)) 	$sql = $sql." goods_name = '".$g_name."',";
				if($cf_id > 0) 		$sql = $sql." cat_id = ".$cf_id.',';
				if(!empty($desc)) 	$sql = $sql." goods_brief = '".$desc."',";
				if(!empty($keywords)) 	$sql = $sql." keywords = '".$keywords."',";
				if(!empty($mark)) 	$sql = $sql." seller_note = '".$mark."',";
				if($size_compare > 0) 	$sql = $sql." size_lib_id = ".$size_compare.",";
				$sql = $sql." goods_sn = goods_sn where goods_sn = '".$code."'";
				
				$db->query($sql);
				
			}
			
			//*********取得商品ID*************
			$sql = " select goods_id from ". $os->table('goods') ." where goods_sn = '".$code."'";
			$p_id = $db->getOne($sql);
			
			//********更新商品商品颜色信息表**************
			
			//商品颜色_色卡编码
			$color_code = $data->sheets[$sheetNo]['cells'][$i][8];
			
			if(!empty($color_code)){
			//首先清空该商品的原有记录
				$sql = " delete  from ". $os->table('goods_color') ." where goods_id = ".$p_id." ";
				$db->query($sql);
				
				$sql = " select * from ". $os->table('color') ." where color_code = '".$color_code."'";
				$res = $db->getRow($sql);
						
				$colorId = $res['color_id'];
				$colorName = $res['color_name'];
				if(!empty($colorId) && !empty($colorName)){
					$sql = " Insert into ".$os->table('goods_color') .
							"(goods_id,goods_sn,color_id,color_name,color_code,adjust_price) values ". 
							"(".$p_id.",'".$code."',".$colorId.",'".$colorName."','".$color_code."',0)";
					$db->query($sql);
				}
				
//				$colors = explode(",",$color_code);
//				foreach($colors as $key=>$value)
//				{
//					$cc = explode("_",$value);
//					if( (!empty($cc[0])) && (!empty($cc[1])) ){
//						
////						获取相对应的颜色和色卡信息
//						$sql = " select * from ". $os->table('color') ." where color_code = '".$cc[0]."'";
//						$res = $db->getRow($sql);
//						
//						$colorId = $res['color_id'];
//						$colorName = $res['color_name'];
//						
//						$sql = " select img_id from ". $os->table('color_lib') ." where img_code = '".$cc[1]."'";
//						$img_id = $db->getOne($sql);
//						
////						向数据库中插入新记录
//						$sql = " Insert into ".$os->table('goods_color') .
//						"(goods_id,color_id,color_name,adjust_price) values ". 
//						"(".$p_id.",".$colorId.",'".$colorName."',0)";
//						
//						$db->query($sql);
//					}
//				}
			}
			
			//********更新商品－尺码信息表**************
			
			//商品尺码编码
			$size_code = $data->sheets[$sheetNo]['cells'][$i][9];
			
			if(!empty($size_code)){
				
				//首先清空该商品的原有记录
				$sql = " delete  from ". $os->table('goods_size') ." where goods_id = ".$p_id." ";
				$db->query($sql);
				
				$sizes = explode(",",$size_code);
				foreach($sizes as $key=>$value)
				{
					//获取相对应的颜色和色卡信息
					$sql = " select * from ". $os->table('size') ." where size_code = '".$value."'";
					$res = $db->getRow($sql);
					
					$sizeId = $res['size_id'];
					$sizeName = $res['size_name'];
					
					if(!empty($sizeId) && !empty($sizeName)){
						//向数据库中插入新记录
						$sql = " Insert into ".$os->table('goods_size') .
						"(goods_id,goods_sn,size_id,size_code,size_name,adjust_price) values ". 
						"(".$p_id.",'".$code."',".$sizeId.",'".$value."','".$sizeName."',0 )";
						$db->query($sql);
					}
				}
				
			}
			
			//********更新商品－关联信息表**************
			
			//关联商品编码
//			$relative_p_code = $data->sheets[$sheetNo]['cells'][$i][9];
//			if(!empty($color_code))
//			{
//				
//				//首先清空该商品的原有记录
//				$sql = " delete  from ". $os->table('group_goods') ." where parent_id = ".$p_id." ";
//				$db->query($sql);
//				
//				$good_s = explode(",",$relative_p_code);
//				foreach($good_s as $key=>$value)
//				{
//					//获取相对应的颜色和色卡信息
//					$sql = " select goods_id,shop_price from ". $os->table('goods') ." where goods_sn = '".$value."'";
//					$res = $db->getRow($sql);
//					
//					$goodsId = $res['goods_id'];
//					$goodsPrice = $res['shop_price'];
//					
//					if(!empty($goodsId)){
//						//向数据库中插入新记录
//						$sql = " Insert into ".$os->table('group_goods') .
//						"(parent_id,goods_id,goods_price,admin_id) values ". 
//						"(".$p_id.",".$goodsId.",'".$goodsPrice."',0 )";
//						
//						$db->query($sql);
//					}
//				}
//				
//			}
		}
		
		//××××××××××××××××处理第二张表【商品图片】，从第2行开始取数据×××××××××××××××××××××
		
//		$sheetNo = 1; 
//		for ($i = 2; $i <= $data->sheets[$sheetNo]['numRows']; $i++) {
//			
//			$p_code = $data->sheets[$sheetNo]['cells'][$i][1];
//			$p_color_code = $data->sheets[$sheetNo]['cells'][$i][2];
//			$p_path = $data->sheets[$sheetNo]['cells'][$i][3];
//			$p_type = $data->sheets[$sheetNo]['cells'][$i][4];
//			$p_rank = $data->sheets[$sheetNo]['cells'][$i][5];
//			$p_desc = $data->sheets[$sheetNo]['cells'][$i][6];
//			
//			//取得商品ID
//			$sql = " select goods_id from ". $os->table('goods') ." where goods_sn = '".$p_code."'";
//			$p_id = $db->getOne($sql);
//			
//			//取得颜色ID
//			$sql = " select color_id from ". $os->table('color') ." where color_code = '".$p_color_code."'";
//			$color_id = $db->getOne($sql);
//			
//			if( (!empty($p_path)) && (!empty($p_id)) && (!empty($color_id)) ){
//				
//				//如果编码是"000"则更新商品的主图片
//				if( ($p_code == "000") && (!empty($p_path)) ){
//					$sql = "Update " . $os->table('goods') . " SET ";
//					$sql = $sql." goods_thumb = '".$p_path."',";
//					$sql = $sql." goods_img = '".$p_path."',";
//					$sql = $sql." original_img = '".$p_path."' ";
//					$sql = $sql." where goods_id = '".$p_id."'";
//					$db->query($sql);
//				}else{
//					$sql = " Insert into ".$os->table('goods_gallery') .
//						"(goods_id,color_id,img_url,thumb_url,img_original) values ". 
//						"(".$p_id.",".$color_id.",'".$p_path."','".$p_path."','".$p_path."')";
//					$db->query($sql);
//				}
//			}
//			
//		}
		
		//××××××××××××××××处理第三张表【色卡信息】，从第2行开始取数据×××××××××××××××××××××
		
		//$sheetNo = 2; 
		
		//for ($i = 2; $i <= $data->sheets[$sheetNo]['numRows']; $i++) {
			//$card_name = $data->sheets[$sheetNo]['cells'][$i][1];
			//$card_code = $data->sheets[$sheetNo]['cells'][$i][2];
			//$card_path = $data->sheets[$sheetNo]['cells'][$i][3];
			
			//if( (!empty($card_name)) && (!empty($card_code)) && (!empty($card_path)) ){
				//$sql = " Insert into ".$os->table('color_lib') .
							//"(img_name,img_code,img_file) values ". 
							//"('".$card_name."','".$card_code."','".$card_path."')";
				//$db->query($sql);
			//}
		//}
	}
    $link[] = array('href' => 'goods.php?act=list', 'text' => '商品列表');
    sys_msg('数据批量初始上传成功', 0, $link);
    
}
elseif($_REQUEST['act']=='edit_spec')
{
 	$smarty->display('spec_batch_info.tpl');	   	
}
/*------------------------------------------------------ */
//-- 批量上传：入库
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert')
{
    /* 检查权限 */
    admin_priv('goods_batch');

    if (isset($_POST['checked']))
    {
        include_once(ROOT_PATH . 'includes/cls_image.php');
        $image = new cls_image($_CFG['bgcolor']);

        /* 字段默认值 */
        $default_value = array(
            'brand_id'      => 0,
            'goods_number'  => 0,
            'goods_weight'  => 0,
            'market_price'  => 0,
            'shop_price'    => 0,
            'warn_number'   => 0,
            'is_real'       => 1,
            'is_on_sale'    => 1,
            'is_alone_sale' => 1,
            'integral'      => 0,
            'is_best'       => 0,
            'is_new'        => 0,
            'is_hot'        => 0,
            'goods_type'    => 0,
        );

        /* 查询品牌列表 */
        $brand_list = array();
        $sql = "SELECT brand_id, brand_name FROM " . $os->table('brand');
        $res = $db->query($sql);
        while ($row = $db->fetchRow($res))
        {
            $brand_list[$row['brand_name']] = $row['brand_id'];
        }

        /* 字段列表 */
        $field_list = array_keys($_LANG['upload_goods']);
        $field_list[] = 'goods_class'; //实体或虚拟商品

        /* 获取商品good id */
        $max_id = $db->getOne("SELECT MAX(goods_id) + 1 FROM ".$os->table('goods'));

        /* 循环插入商品数据 */
        foreach ($_POST['checked'] AS $key => $value)
        {
            // 合并
            $field_arr = array(
                'cat_id'        => $_POST['cat'],
                'add_time'      => gmtime(),
                'last_update'   => gmtime(),
            );

            foreach ($field_list AS $field)
            {
                // 转换编码
                $field_value = isset($_POST[$field][$value]) ? $_POST[$field][$value] : '';

                /* 虚拟商品处理 */
                if ($field == 'goods_class')
                {
                    $field_value = intval($field_value);
                    if ($field_value == G_CARD)
                    {
                        $field_arr['extension_code'] = 'virtual_card';
                    }
                    continue;
                }

                // 如果字段值为空，且有默认值，取默认值
                $field_arr[$field] = !isset($field_value) && isset($default_value[$field]) ? $default_value[$field] : $field_value;

                // 特殊处理
                if (!empty($field_value))
                {
                    // 图片路径
                    if (in_array($field, array('original_img', 'goods_img', 'goods_thumb')))
                    {
                        $field_arr[$field] = IMAGE_DIR . '/' . $field_value;
                    }
                    // 品牌
                    elseif ($field == 'brand_name')
                    {
                        if (isset($brand_list[$field_value]))
                        {
                            $field_arr['brand_id'] = $brand_list[$field_value];
                        }
                        else
                        {
                            $sql = "INSERT INTO " . $os->table('brand') . " (brand_name) VALUES ('" . addslashes($field_value) . "')";
                            $db->query($sql);
                            $brand_id = $db->insert_id();
                            $brand_list[$field_value] = $brand_id;
                            $field_arr['brand_id'] = $brand_id;
                        }
                    }
                    // 整数型
                    elseif (in_array($field, array('goods_number', 'warn_number', 'integral')))
                    {
                        $field_arr[$field] = intval($field_value);
                    }
                    // 数值型
                    elseif (in_array($field, array('goods_weight', 'market_price', 'shop_price')))
                    {
                        $field_arr[$field] = floatval($field_value);
                    }
                    // bool型
                    elseif (in_array($field, array('is_best', 'is_new', 'is_hot', 'is_on_sale', 'is_alone_sale', 'is_real')))
                    {
                        $field_arr[$field] = intval($field_value) > 0 ? 1 : 0;
                    }
                }
                if ($field == 'is_real')
                {
                    $field_arr[$field] = intval($_POST['goods_class'][$key]);
                }
            }

            if (empty($field_arr['goods_sn']))
            {
                $field_arr['goods_sn'] = generate_goods_sn($max_id);
            }

            /* 如果是虚拟商品，库存为0 */
            if ($field_arr['is_real'] == 0)
            {
                $field_arr['goods_number'] = 0;
            }
            $db->autoExecute($os->table('goods'), $field_arr, 'INSERT');
            $last_goods_id = $db->insert_id();
            if(!empty($field_arr['color_spec'])){
                     insert_batch_goods_spec('color',$field_arr['color_spec'],$last_goods_id);
            }
            if(!empty($field_arr['size_spec'])){
                     insert_batch_goods_spec('size',$field_arr['size_spec'],$last_goods_id);
            }
            $max_id = $db->insert_id() + 1;

            /* 如果图片不为空,修改商品图片，插入商品相册*/
            if (!empty($field_arr['original_img']) || !empty($field_arr['goods_img']) || !empty($field_arr['goods_thumb']))
            {
                $goods_img     = '';
                $goods_thumb   = '';
                $original_img  = '';
                $goods_gallery = array();
                $goods_gallery['goods_id'] = $db->insert_id();

                if (!empty($field_arr['original_img']))
                {
                    //设置商品相册原图和商品相册图
                    if ($_CFG['auto_generate_gallery'])
                    {
                        $ext         = substr($field_arr['original_img'], strrpos($field_arr['original_img'], '.'));
                        $img         = dirname($field_arr['original_img']) . '/' . $image->random_filename() . $ext;
                        $gallery_img = dirname($field_arr['original_img']) . '/' . $image->random_filename() . $ext;
                        @copy(ROOT_PATH . $field_arr['original_img'], ROOT_PATH . $img);
                        @copy(ROOT_PATH . $field_arr['original_img'], ROOT_PATH . $gallery_img);
                        $goods_gallery['img_original'] = reformat_image_name('gallery', $goods_gallery['goods_id'], $img, 'source');
                    }
                    //设置商品原图
                    if ($_CFG['retain_original_img'])
                    {
                        $original_img                  = reformat_image_name('goods', $goods_gallery['goods_id'], $field_arr['original_img'], 'source');
                    }
                    else
                    {
                        @unlink(ROOT_PATH . $field_arr['original_img']);
                    }
                }

                if (!empty($field_arr['goods_img']))
                {
                    //设置商品相册图
                    if ($_CFG['auto_generate_gallery'] && !empty($gallery_img))
                    {
                        $goods_gallery['img_url'] = reformat_image_name('gallery', $goods_gallery['goods_id'], $gallery_img, 'goods');
                    }
                    //设置商品图
                    $goods_img                = reformat_image_name('goods', $goods_gallery['goods_id'], $field_arr['goods_img'], 'goods');
                }

                if (!empty($field_arr['goods_thumb']))
                {
                    //设置商品相册缩略图
                    if ($_CFG['auto_generate_gallery'])
                    {
                        $ext           = substr($field_arr['goods_thumb'], strrpos($field_arr['goods_thumb'], '.'));
                        $gallery_thumb = dirname($field_arr['goods_thumb']) . '/' . $image->random_filename() . $ext;
                        @copy(ROOT_PATH . $field_arr['goods_thumb'], ROOT_PATH . $gallery_thumb);
                        $goods_gallery['thumb_url'] = reformat_image_name('gallery_thumb', $goods_gallery['goods_id'], $gallery_thumb, 'thumb');
                    }
                    //设置商品缩略图
                    $goods_thumb = reformat_image_name('goods_thumb', $goods_gallery['goods_id'], $field_arr['goods_thumb'], 'thumb');
                }

                //修改商品图
                $db->query("UPDATE " . $os->table('goods') . " SET goods_img = '$goods_img', goods_thumb = '$goods_thumb', original_img = '$original_img' WHERE goods_id='" . $goods_gallery['goods_id'] . "'");

                //添加商品相册图
                if ($_CFG['auto_generate_gallery'])
                {
                    $db->autoExecute($os->table('goods_gallery'), $goods_gallery, 'INSERT');
                }
            }
        }
    }
    drop_tmp_batch_goods_csv();
    // 记录日志
    admin_log('', 'batch_upload', 'goods');

    /* 显示提示信息，返回商品列表 */
    $link[] = array('href' => 'goods.php?act=list', 'text' => '商品列表');
    sys_msg('批量上传成功', 0, $link);
}

/*------------------------------------------------------ */
//-- 批量修改：选择商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'select')
{
    /* 检查权限 */
    admin_priv();

    /* 取得分类列表 */
    $smarty->assign('cat_list', cat_list());

    /* 取得品牌列表 */
    $smarty->assign('brand_list', get_brand_list());

    /* 参数赋值 */
    $smarty->assign('ur_here', '商品批量修改');

    /* 显示模板 */
    assign_query_info();
	
	$smarty->display('goods_batch_select.tpl');
}

/*------------------------------------------------------ */
//-- 批量修改：修改
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('edit_goods_batch');

    /* 取得商品列表 */
    if ($_POST['select_method'] == 'cat')
    {
        $where = " WHERE goods_id " . db_create_in($_POST['goods_ids']);
    }
    else
    {
        $goods_sns = str_replace("\n", ',', str_replace("\r", '', $_POST['sn_list']));
        $sql = "SELECT DISTINCT goods_id FROM " . $os->table('goods') .
                " WHERE goods_sn " . db_create_in($goods_sns);
        $goods_ids = join(',', $db->getCol($sql));
        $where = " WHERE goods_id " . db_create_in($goods_ids);
    }
    $sql = "SELECT DISTINCT goods_id, goods_sn, goods_name, market_price, shop_price, goods_number, integral, give_integral, brand_id, is_real FROM " . $os->table('goods') . $where;
    $smarty->assign('goods_list', $db->getAll($sql));

    /* 取得客户价格 */
    $member_price_list = array();
    $sql = "SELECT DISTINCT goods_id, user_rank, user_price FROM " . $os->table('member_price') . $where;
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $member_price_list[$row['goods_id']][$row['user_rank']] = $row['user_price'];
    }
    $smarty->assign('member_price_list', $member_price_list);

    /* 取得客户等级 */
    $sql = "SELECT rank_id, rank_name, discount " .
            "FROM " . $os->table('user_rank') .
            " ORDER BY discount DESC";
    $smarty->assign('rank_list', $db->getAll($sql));

    /* 取得品牌列表 */
    $smarty->assign('brand_list', get_brand_list());

    /* 赋值编辑方式 */
    $smarty->assign('edit_method', $_POST['edit_method']);

    /* 参数赋值 */
    $smarty->assign('ur_here', '商品批量修改');

    /* 显示模板 */
    assign_query_info();
    
    $smarty->display('goods_batch_edit.tpl');   
}

/*------------------------------------------------------ */
//-- 批量修改：提交
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'update')
{
    /* 检查权限 */
    admin_priv('edit_goods_batch');

    if ($_POST['edit_method'] == 'each')
    {
        // 循环更新每个商品
        if (!empty($_POST['goods_id']))
        {
            foreach ($_POST['goods_id'] AS $goods_id)
            {
                // 更新商品
                $goods = array(
                    'market_price'  => floatval($_POST['market_price'][$goods_id]),
                    'shop_price'    => floatval($_POST['shop_price'][$goods_id]),
                    'integral'      => intval($_POST['integral'][$goods_id]),
                    'give_integral'      => intval($_POST['give_integral'][$goods_id]),
                    'goods_number'  => intval($_POST['goods_number'][$goods_id]),
                    'brand_id'      => intval($_POST['brand_id'][$goods_id]),
                    'last_update'   => gmtime(),
                );
                $db->autoExecute($os->table('goods'), $goods, 'UPDATE', "goods_id = '$goods_id'");

                // 更新客户价格
                if (!empty($_POST['rank_id']))
                {
                    foreach ($_POST['rank_id'] AS $rank_id)
                    {
                        if (trim($_POST['member_price'][$goods_id][$rank_id]) == '')
                        {
                            /* 为空时不做处理 */
                            continue;
                        }

                        $rank = array(
                            'goods_id'  => $goods_id,
                            'user_rank' => $rank_id,
                            'user_price'=> floatval($_POST['member_price'][$goods_id][$rank_id]),
                        );
                        $sql = "SELECT COUNT(*) FROM " . $os->table('member_price') . " WHERE goods_id = '$goods_id' AND user_rank = '$rank_id'";
                        if ($db->getOne($sql) > 0)
                        {
                            if ($rank['user_price'] < 0)
                            {
                                $db->query("DELETE FROM " . $os->table('member_price') . " WHERE goods_id = '$goods_id' AND user_rank = '$rank_id'");
                            }
                            else
                            {
                                $db->autoExecute($os->table('member_price'), $rank, 'UPDATE', "goods_id = '$goods_id' AND user_rank = '$rank_id'");
                            }

                        }
                        else
                        {
                            if ($rank['user_price'] >= 0)
                            {
                                $db->autoExecute($os->table('member_price'), $rank, 'INSERT');
                            }
                        }
                    }
                }
            }
        }
    }
    else
    {
        // 循环更新每个商品
        if (!empty($_POST['goods_id']))
        {
            foreach ($_POST['goods_id'] AS $goods_id)
            {
                // 更新商品
                $goods = array();
                if (trim($_POST['market_price'] != ''))
                {
                    $goods['market_price'] = floatval($_POST['market_price']);
                }
                if (trim($_POST['shop_price']) != '')
                {
                    $goods['shop_price'] = floatval($_POST['shop_price']);
                }
                if (trim($_POST['integral']) != '')
                {
                    $goods['integral'] = intval($_POST['integral']);
                }
                if (trim($_POST['give_integral']) != '')
                {
                    $goods['give_integral'] = intval($_POST['give_integral']);
                }
                if (trim($_POST['goods_number']) != '')
                {
                    $goods['goods_number'] = intval($_POST['goods_number']);
                }
                if ($_POST['brand_id'] > 0)
                {
                    $goods['brand_id'] = $_POST['brand_id'];
                }
                if (!empty($goods))
                {
                    $db->autoExecute($os->table('goods'), $goods, 'UPDATE', "goods_id = '$goods_id'");
                }

                // 更新客户价格
                if (!empty($_POST['rank_id']))
                {
                    foreach ($_POST['rank_id'] AS $rank_id)
                    {
                        if (trim($_POST['member_price'][$rank_id]) != '')
                        {
                            $rank = array(
                                        'goods_id'  => $goods_id,
                                        'user_rank' => $rank_id,
                                        'user_price'=> floatval($_POST['member_price'][$rank_id]),
                                        );

                            $sql = "SELECT COUNT(*) FROM " . $os->table('member_price') . " WHERE goods_id = '$goods_id' AND user_rank = '$rank_id'";
                            if ($db->getOne($sql) > 0)
                            {
                                if ($rank['user_price'] < 0)
                                {
                                    $db->query("DELETE FROM " . $os->table('member_price') . " WHERE goods_id = '$goods_id' AND user_rank = '$rank_id'");
                                }
                                else
                                {
                                    $db->autoExecute($os->table('member_price'), $rank, 'UPDATE', "goods_id = '$goods_id' AND user_rank = '$rank_id'");
                                }

                            }
                            else
                            {
                                if ($rank['user_price'] >= 0)
                                {
                                    $db->autoExecute($os->table('member_price'), $rank, 'INSERT');
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // 记录日志
    admin_log('', 'batch_edit', 'goods');

    // 提示成功
    $link[] = array('href' => 'goods_batch.php?act=select', 'text' => '商品批量修改');
    sys_msg('批量修改成功', 0, $link);
}

/*------------------------------------------------------ */
//-- 下载文件
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'download')
{
    /* 检查权限 */
    admin_priv('goods_batch');
	
    // 文件标签
    // Header("Content-type: application/octet-stream");
    header("Content-type: application/vnd.ms-excel; charset=utf-8");
    Header("Content-Disposition: attachment; filename=goods_list.csv");
	
    die(SOURCE_PATH);
    
    // 下载
    if ($_GET['charset'] != $_CFG['lang'])
    {
        $lang_file = SOURCE_PATH.'languages/' . $_GET['charset'] . '/admin/goods_batch.php';
        if (file_exists($lang_file))
        {
            unset($_LANG['upload_goods']);
            require($lang_file);
        }
    }
    if (isset($_LANG['upload_goods']))
    {
        /* 创建字符集转换对象 */
        if ($_GET['charset'] == 'zh_cn' || $_GET['charset'] == 'zh_tw')
        {
            $to_charset = $_GET['charset'] == 'zh_cn' ? 'GB2312' : 'BIG5';
            echo os_iconv(OS_CHARSET, $to_charset, join(',', $_LANG['upload_goods']));
        }
        else
        {
            echo join(',', $_LANG['upload_goods']);
        }
    }
    else
    {
        echo 'error: $_LANG[upload_goods] not exists';
    }
}

/*------------------------------------------------------ */
//-- 取得商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'get_goods')
{
    $filter = &new stdclass;

    $filter->cat_id = intval($_GET['cat_id']);
    $filter->brand_id = intval($_GET['brand_id']);
    $filter->real_goods = -1;
    $arr = get_goods_list($filter);

    make_json_result($arr);
}

function insert_spec_batch($arr){
	//created at 2009-05-03  author:fillbag
    switch ($arr['type']){
    	default:return false;
    	case 'color':
      	case 'size':    		
    		$arr_opt = array();
    		if($arr['value']){
    			$arr_opt = explode(';',rtrim($arr['value'],';'));
    		}    	
            if(sizeof($arr_opt)>0){
	    		$txt = ''; $val = ''; $img_val = ''; $i = 0;
	    		foreach($arr_opt as $opt_item){
		    		if($arr['type']=='color'){		    		
						$sql = "SELECT color_id,color_code FROM ".$GLOBALS['os']->table('color')." WHERE color_code='".
						       ( strpos($opt_item,':')===false ? $opt_item : substr($opt_item,0,strpos($opt_item,':')))."' ORDER BY color_id DESC LIMIT 1";
						$sel_color_row = $GLOBALS['db']->getRow($sql);
						if($sel_color_row && $sel_color_row['color_id']>0){
							$i++;
							$txt .= $sel_color_row['color_code'];
							$val .= $sel_color_row['color_id'];
						}
						$img_code = substr($opt_item,strpos($opt_item,':')+1);
						if($sel_color_row && strpos($opt_item,':')!==false && trim($img_code)!=''){
							//$sql = "SELECT img_id,img_code FROM ".$GLOBALS['os']->table('color_lib')." WHERE img_code='$img_code' ORDER BY img_id DESC LIMIT 1";
							//$sel_img_row = $GLOBALS['db']->getRow($sql);
							//if($sel_img_row && $sel_img_row['img_id']>0){
							   //$txt .= ':'.$sel_img_row['img_code'];
							   //$img_val .= $sel_img_row['img_id'];
							//}else{
						 	  // $img_val .= 0;
							//}
						}else{
			                $img_val .= 0;
						}
		    		}else{
						$sql = "SELECT size_id,size_code FROM ".$GLOBALS['os']->table('size')." WHERE size_code='$opt_item' ORDER BY size_id DESC LIMIT 1";
						$sel_size_row = $GLOBALS['db']->getRow($sql);
						if($sel_size_row && $sel_size_row['size_id']>0){
							$i++;
							$txt .= $sel_size_row['size_code'];
							$val .= $sel_size_row['size_id'];
						}		    			
		    		}
		    		$txt .= $i>0 ? ';' : '';	
		    		$val .= $i>0 ? ',' : '';
		    		$img_val .= $i>0 ? ',' : '';
	    	    }
            } 			
    		break;
    }
    return '<input type="text" name="'.$arr['type'].'_spec[]" size="15" value="'.rtrim($txt,';').'"/>';		
}

function insert_batch_goods_spec($type,$data,$goods_id){
	//created at 2009-05-03  author:fillbag
    switch ($type){
    	default:return false;
    	case 'color':
      	case 'size':    		
    		$arr_opt = array();
    		if(trim($data) != ''){
    			$arr_opt = explode(';',rtrim($data,';'));
    		}    	
            if(sizeof($arr_opt)>0){
	    		foreach($arr_opt as $opt_item){
		    		if($type=='color'){		    		
						$sql = "SELECT color_id,color_name FROM ".$GLOBALS['os']->table('color')." WHERE color_code='".
						       ( strpos($opt_item,':')===false ? $opt_item : substr($opt_item,0,strpos($opt_item,':')))."' ORDER BY color_id DESC LIMIT 1";
						$sel_color_row = $GLOBALS['db']->getRow($sql);
						if($sel_color_row && $sel_color_row['color_id']>0){							
							$img_code = substr($opt_item,strpos($opt_item,':')+1);
							if(strpos($opt_item,':')!==false && trim($img_code)!=''){
								//$sql = "SELECT img_id FROM ".$GLOBALS['os']->table('color_lib')." WHERE img_code='$img_code' ORDER BY img_id DESC LIMIT 1";
								//$sel_img_id = $GLOBALS['db']->getOne($sql);
								//if(!$sel_img_id || $sel_img_id<=0){
							 	   //$sel_img_id = 0;
								//}								
							}else{
			                	$sel_img_id = 0;
							}
							$tmp_sql = "INSERT INTO ".$GLOBALS['os']->table('goods_color')."(goods_id,color_id,color_name,img_id)".
							           " VALUES('$goods_id','$sel_color_row[color_id]','$sel_color_row[color_name]','$sel_img_id');";
							           //die($tmp_sql); 
                        	$GLOBALS['db']->query($tmp_sql);
						}
		    		}else{
						$sql = "SELECT size_id,size_name FROM ".$GLOBALS['os']->table('size')." WHERE size_code='$opt_item' ORDER BY size_id DESC LIMIT 1";
						$sel_size_row = $GLOBALS['db']->getRow($sql);
						if($sel_size_row && $sel_size_row['size_id']>0){
							$tmp_sql = "INSERT INTO ".$GLOBALS['os']->table('goods_size')."(goods_id,size_id,size_name)".
							           " VALUES('$goods_id','$sel_size_row[size_id]','$sel_size_row[size_name]');";
                        	$GLOBALS['db']->query($tmp_sql);
						}		    			
		    		}
	    	    }
            } 			
    		break;
    }
}

function drop_tmp_batch_goods_csv($ext=''){

	if(file_exists(SOURCE_PATH.'temp/goods_package/'.$file))
	{
		$dir = opendir(SOURCE_PATH.'temp/goods_package/'.$file);	
	    while (@$file = readdir($dir))
	    {
	        if ($file != '.' && $file != '..' && $file != ".svn" && $file != "_svn" && is_dir(SOURCE_PATH.'temp/goods_package/'.$file) !== true  && fileext($file)!='zip')
	        {
	            @unlink(SOURCE_PATH.'temp/goods_package/'.$file);
	        }
	    }
	    @closedir($dir);   
	}
}
?>